#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include <cstdint>

extern Log lg;

class Task
{
public:
    Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
        : sockfd_(sockfd), clientip_(clientip), clientport_(clientport)
    {
    }
    void run()
    {
        char buffer[4096];
        while(true)
        {
            
            ssize_t n = read(sockfd_,buffer,sizeof(buffer));
            if(n>0)
            {
                //打印信息
                buffer[n] = 0;
                std::cout << "client say# " << buffer << std::endl;

                std::string echo_string = "tcpserver echo# ";
                echo_string += buffer;
                write(sockfd_, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                lg(Info, "%s:%d quit, server close sockfd: %d", clientip_.c_str(), clientport_, sockfd_);
                break;
            }
            else
            {
                lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", sockfd_, clientip_.c_str(), clientport_);
                break;
            }
        }
    }
    void operator()()
    {
        run();
    }
    ~Task()
    {
    }

private:
    int sockfd_;
    uint16_t clientport_;
    std::string clientip_;
};